package com.itheima.d1_commun;

/**
 * 接听电话线程
 */
public class ReceiveThread extends Thread {
    private Phone phone;

    public ReceiveThread(Phone phone) {
        this.phone = phone;
    }

    @Override
    public void run() {
        //1.不断的接听电话
        while (true) {
            synchronized (phone) {
                //2.判断电话有没有打出，tag为true的时候可以接听
                if (phone.tag) {
                    System.out.println("接听电话...");
                    try {
                        Thread.sleep(500);

                        //3.电话已经被接听，tag应该改成false
                        phone.tag = false;

                        //4.这个时候打电话的线程可能正在等待，需要把它们唤醒
                        phone.notifyAll();

                        //5.接听电话的不应该去抢夺，它应该等待
                        phone.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
